<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class BaseController extends CI_Controller {

	public function __construct() {
        parent::__construct();

        // 加载session类
        $this->load->library('session');

        // 加载辅助函数库
        $this->load->helper('url');

        // 加载公用帮助类
        $this->load->helper('common');
        $this->load->helper('str');
        
        // 后台静态页面
        $this->staticUrl = site_url(APPLICATION_FOLDER. "/views/");
        $this->staticAdminUrl = $this->staticUrl. ADMIN_DIR. "/";
        // 班牌手机端静态页面，brand_api使用到
        $this->staticWxUrl = $this->staticUrl . WX_DIR . "/";
        // 官网页面
        $this->staticHomeUrl = $this->staticUrl. "home/"; 
    }

    // 后台初始化方法
    public function admin_init(){
        // 判断用户是否登录，没有就跳转到登录页面
        // echo'<pre>';var_export($this->session);exit;
        if(!$this->session->rmxUser) {
            $redirectUrl = admin_url("login");
            redirect($redirectUrl);
        }
        // 后台标题
        $this->adminTitle = "管理系统";
        // 获取后台模块方法
        $this->menuLink = $this->router->fetch_class(). "/". $this->router->fetch_method();
        $this->check_admin_menu_role($this->menuLink);
        // 获取数据
        $this->rmxUser = $this->session->rmxUser;               // 获取用户信息
        $this->userType = $this->rmxUser['user_type'];          // 获取角色身份
        // 如果是老师或者学校管理员
        if($this->userType == USER_TYPE_SCHOOL || $this->userType == USER_TYPE_TEACHER) {
            $this->rmxSchool = $this->rmxUser['school'];        // 获取学校信息
            $this->campusInfo = $this->session->campusInfo;     // 获取校区信息
            $this->campusList = $this->session->campusList;     // 获取校区列表
            if(!$this->campusInfo) throw new Exception("参数错误，请重新登录");
        }
    }

    // 移动端初始化方法
    public function wx_init() {

        // 清除缓存，用于调试
        // $this->session->set_userdata('wx', NULL);exit;
        // 选择底部tabbar栏,home => 首页，classes => 菜单，user => 个人中心
        $requestUri = explode('/', $_SERVER['REQUEST_URI']);

        $this->currentTab = isset($requestUri[2]) ? $requestUri[2] : '';

        // 获取缓存数据
        $this->wxSession = $this->session->userdata('wx');
        // 判断是否有重定向url
        if($redirectUrl = $this->session->userdata('redirect_url')) {
            // 置空
            $this->session->set_userdata('redirect_url', NULL);
            // 跳转
            header("Location:" . $redirectUrl);
            exit;
        }

        // var_export($this->wxSession['openid']);exit;

        // 企业微信不需要授权
        if(!isset($this->wxSession['qywx'])) {
            // 判断是否已经授权
            if(!isset($this->wxSession['openid']) || empty($this->wxSession['openid'])) {
                // 未登录就跳到授权页面
                $this->load->library('wechat');
                $this->wechat->authorize();
            }
        }

        // 判断是否已选择账号（[‘绑定账号’,‘选择账号’] 页面 和 [‘选择账号’, ‘’]操作就跳过)
        // 绑定账号页面的uri和选择账号页面的uri
        $bindCardUri = '/' . WX_DIR . '/pub/bind_card';
        $cardUri = '/' . WX_DIR . '/pub/card';
        // 未选择账号
        if((!isset($this->wxSession['user']) || !isset($this->wxSession['bind_user_type']))) {
            // 获取当前url
            $url = site_url($_SERVER['REQUEST_URI']);
            // 设置重定向url
            $this->session->set_userdata('redirect_url', $url);
            // var_export($url);exit;

            $this->load->model('wxUserModel');
            $this->load->model('schoolModel');
            // 获取wx_user
            $wxUser = $this->wxUserModel->get_wx_user_by_openid($this->wxSession['openid']);
            // 判断该openid是否已绑定账号
            $params['isDelete'] = 0;
            // $params['wxUserId'] = empty($wxUser) ? 0 : $wxUser['id'];
            $params['wxUserId'] = empty($wxUser) ? -1 : $wxUser['id'];
            // 已绑定的所有账号
            $bindUsers = $this->wxUserModel->get_bind_user_list($params);

            // 过滤已删除的账号
            if($bindUsers) {
                foreach($bindUsers as $key => $item) {
                    if($item['bind_user_type'] == BIND_TYPE_STUDENT) {
                        $studentInfo = $this->schoolModel->get_student_info($item['bind_user_id']);
                        if($studentInfo['is_delete'] == 1) {
                            unset($bindUsers[$key]);
                        }
                    } else {
                        $teacherInfo = $this->schoolModel->get_school_user_info_realname($item['bind_user_id']);
                        if($teacherInfo['is_delete'] == 1) {
                            unset($bindUsers[$key]);
                        }
                    }
                }
            }

            // var_export($bindUsers);exit;
            // 当openid未绑定账号，跳转到‘绑定账号’页面
            if(empty($bindUsers)) {
                header("Location:" . site_url($bindCardUri));
                exit;
            }

            // 只绑定一个账号，也需要选择账号
            // // 当openid只绑定一个账号，跳转到‘个人中心’页面
            // if(count($bindUsers) === 1) {
            //     // $bindUser = $bindUsers[0];
            //     // 获取第一个元素，兼容下标不是从0开始
            //     $bindUser = array_shift($bindUsers);
            //     $bindUserType = $bindUser['bind_user_type'];
            //     // 获取绑定的用户
            //     if($bindUserType == BIND_TYPE_STUDENT) {
            //         // 获取学生
            //         $user = $this->schoolModel->get_student_info($bindUser['bind_user_id']);
            //     } else {
            //         // 获取教师
            //         $user = $this->schoolModel->get_school_user_info_realname($bindUser['bind_user_id']);
            //     }
            //     // session设置登录的user
            //     if(empty($this->wxSession)) {
            //         $sessArr = array(
            //             'user' => $user,
            //             'bind_user_type' => $bindUserType
            //         );
            //     } else {
            //         $sessArr = array_merge($this->wxSession, array(
            //             'user' => $user,
            //             'bind_user_type' => $bindUserType
            //         ));
            //     }
            //     $this->session->set_userdata('wx', $sessArr);
            //     header("Location:" . site_url('/' . WX_DIR . '/user/index'));
            //     exit;
            // }

            // 当openid已绑定多个账号，跳转到‘选择账号’页面
            header("Location:" . site_url($cardUri));
            exit;
        }
        // 页面设置绑定的用户信息和用户类型，避免长时间缓存，页面上是旧的用户信息
        if(isset($this->wxSession['user']) && isset($this->wxSession['bind_user_type'])) {
            // 刷新用户信息
            $this->_save_user_info();

            // 设置未读数
            $unreadURIArr = array(
                '/' . WX_DIR . '/home/index',
                '/' . WX_DIR . '/menu/index',
                '/' . WX_DIR . '/user/index'
            );
            // 还包含作业，动态，通知详情页面
            if(in_array($_SERVER['REQUEST_URI'], $unreadURIArr) || strstr($_SERVER['REQUEST_URI'], '_detail')) {
                // 获取未读数
                $this->_get_unread_count();
            }
        }
    }

    private function _save_user_info() {
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $user = array();
        $sessUser = $this->wxSession['user'];
        $sessUserType = $this->wxSession['bind_user_type'];
        if($sessUser && $sessUserType) {
            if($sessUserType == BIND_TYPE_STUDENT) {
                // 获取学生信息
                $user = $this->schoolModel->get_student_info($sessUser['id']);
                // 获取学生所在班级名称
                $class = $this->classesModel->get_class_info($user['class_id']);
                if(!empty($class)) {
                    $user['class'] = $class;
                }
                // 获取学校过期时间
                $schoolInfo = $this->schoolModel->get_school_info($user['school_id']);
                if($schoolInfo['expire_date']) {
                    $schoolExpireDate = $schoolInfo['expire_date'];
                    $studentExpireDate = $user['expire_date'];
                    if($studentExpireDate) {
                        if($studentExpireDate > $schoolExpireDate) {
                            $expireDate = $studentExpireDate;
                        } else {
                            $expireDate = $schoolExpireDate;
                        }
                    } else {
                        $expireDate = $schoolExpireDate;
                    }
                    if($expireDate < date('Y-m-d', strtotime('+7 days'))) {
                        $user['expiredSoon'] = 1;
                        if($expireDate < date('Y-m-d')) {
                            $user['expired'] = 1;
                        } else {
                            $user['expired'] = 0;
                        }
                    } else {
                        $user['expired'] = 0;
                        $user['expiredSoon'] = 0;
                    }
                } else {
                    $user['expired'] = 0;
                    $user['expiredSoon'] = 0;
                }

                // 判断是否限制增值功能
                if($user['is_limit'] == 1) {
                    $user['expiredSoon'] = 1;
                    $user['expired'] = 1;
                }
                
            } else {
                // 获取教师信息
                $user = $this->schoolModel->get_school_user_info_realname($sessUser['id']);
                // // 获取教师任课班级名称             
                // if(!empty($sessUser['class_ids'])) {
                //     $user['classNameStr'] = $this->_get_class_name_str($sessUser['class_ids']);
                // }
                // 是否过期
                $user['expired'] = 0;
                $user['expiredSoon'] = 0;
            }
        }
        // var_export($user['expired']);var_export($user['expiredSoon']);exit;
        $this->user = $user;
        $this->bindUserType = $sessUserType;
    }

    private function _get_unread_count() {
        $this->load->model('contentModel');
        $this->load->model('wxUserModel');
        $this->load->model('wxAppliModel');
        // 待办事项
        $countUnread = array();
        // 获取学生待办事项
        if($this->bindUserType == BIND_TYPE_STUDENT) {
            // 未读作业
            $homeworkUnread = $this->_get_homework_unread();

            // 设置未读数
            $countUnread['homework'] = $homeworkUnread['count'];
        }

        // 获取教师待办事项
        if($this->bindUserType == BIND_TYPE_TEACHER) {
            // // 未读邮件
            // $mailUnread = $this->_get_mail_unread();
            // // 设置未读数，暂无
            // // 未读申请审批
            // $applicationUnread = $this->_get_application_unread();

        }

        // 未读班牌留言
        $countUnread['note'] = $this->_get_note_unread(0);
        // 未读班牌留言
        $countUnread['brand_note'] = $this->_get_note_unread(1);

        // 设置未读数
        $this->countUnread = $countUnread;
        // 设置未读总数
        $countUnreadAll = 0;
        // 设置已选菜单的未读总数
        $countUserUnreadAll = 0;
        // 获取所有应用
        $params['bindUserType'] = $this->bindUserType;
        $params['isDelete'] = 0;
        // 排序
        $params['orderBy'] = 'sort_level DESC';
        $applications = $this->wxAppliModel->get_wx_application_list($params);
        // 获取当前用户应用
        $params['userId'] = $this->user['id'];
        $userAppli = $this->wxAppliModel->get_wx_user_appli($params);
        $userAppliIdArr = array();
        if($userAppli) {
            // 用户已添加过
            $userAppliIdArr = explode(',', $userAppli['appli_ids']);
            // 兼容之前可以8个
            if(count($userAppliIdArr) === 8) {
                array_pop($userAppliIdArr);
            }
        } else {
            // 如未添加过，默认已添加前7个应用
            foreach($applications as $key => $application) {
                if($key < 7) {
                    array_push($userAppliIdArr, $application['id']);
                }
            }
        }
        foreach($countUnread as $key => $count) {
            if($count > 0) {
                $countUnreadAll += $count;
                // 获取菜单id
                $application = $this->wxAppliModel->get_wx_application_by_value($key, $this->bindUserType);
                // 判断是否已选菜单
                if(in_array($application['id'], $userAppliIdArr)) {
                    $countUserUnreadAll += $count;
                }
            }
            if($count > 99) {
                $countUnread[$key] = '99+';
            }
        }
        if($countUnreadAll > 99) {
            $countUnreadAll = '99+';
        }
        if($countUserUnreadAll > 99) {
            $countUserUnreadAll = '99+';
        }
        $this->countUnreadAll = $countUnreadAll;
        $this->countUserUnreadAll = $countUserUnreadAll;
    }

    // 加载页面试图
    protected function display($viewName){
    	$this->load->view($viewName, $this);
    }

    // 加载页面试图,能够接收请求数据
    protected function displayWithData($viewName, $data){
        $that = $this;
        $that->data = $data;
        $this->load->view($viewName, $that);
    }

    // 重新映射方法
    public function _remap($method, $params = array()) {
        try{
            return call_user_func_array(array($this, $method), $params);
            // $this->$method();
        }catch(Exception $e) {
            exit(json($e->getMessage()));
        }
    }

    // 获取get参数
    public function get($key, $cleanXss = true) {
        return $this->input->get($key, $cleanXss);
    }
    // 获取post参数
    public function post($key, $cleanXss = true) {
        return $this->input->post($key, $cleanXss);
    }
    // 检查数据有效性
    public function check_data_valid($data, $checkExits = false, $checkDelete = false, $checkSchoolId = false, $checkCampusId = false, $checkUserId = false) {
        if($checkExits && !$data) throw new Exception("参数错误，请刷新后重试");
        if($checkDelete && $data['is_delete']) throw new Exception("参数错误，请刷新后重试");
        if($checkSchoolId && $data['school_id'] != $this->rmxSchool['id']) throw new Exception("参数错误，请刷新后重试");
        if($checkCampusId && $data['campus_id'] != $this->campusInfo['id']) throw new Exception("参数错误，请刷新后重试");
        if($checkUserId && $data['user_id'] != $checkUserId) throw new Exception("参数错误，请刷新后重试");
    }

    // 检查菜单权限
    public function check_admin_menu_role(&$menuLink){
        switch($menuLink) {
            // 不需要鉴权的菜单
            case "home/logout":
            case "home/password":
            case "home/select_campus":
            case "home/modify_password_action":
            case "home/index":
            case "admin/index":
            case "school/index":
            case "school/select_teacher_plugin_data_source":
            case "school/get_class_list":
            case "tool/index":      // 自动更新缺漏数据工具
            case "setting/save_sync_log_action": // 插入日志，教师都有权限
                return;
            // 超管：学校管理
            case "admin/get_school_list":
            case "admin/school_edit":
            case "admin/hzy_school_edit":
            case "admin/save_school_action":
            case "admin/save_hzy_school_action":
            case "admin/get_school_user_action":
            case "admin/reset_school_user_password":
            case "admin/save_school_account_action":
            case "admin/delete_school_user":
            case "admin/brand":                         // 班牌管理
            case "admin/get_brand_list":                // 获取班牌列表
            case "admin/save_brand_action":             // 保存班牌
            case "admin/campus":                        // 校区管理
            case "admin/get_campus_list":               // 获取校区列表
            case "admin/save_campus_action":            // 保存校区信息
            case "admin/delete_campus_action":          // 删除校区信息
            case "admin/get_admin_date_student_num":    // 获取全部学校当日人数统计
            case "admin/get_admin_work_data_num":       // 获取全部学校作业量统计
            case "admin/charge":                        // 收费管理
            case "admin/get_charge_list":               // 获取收费列表
            case "admin/save_charge_action":            // 保存收费信息
            case "admin/delete_charge_action":          // 删除收费信息
            case "admin/save_sync_log_action":             // 插入日志
            case "admin/brand_batch":                   // 批量添加班牌
            case "admin/save_brand_batch_action":       // 批量添加班牌
                $menuLink = "admin/school";
                break;
            // 超管：操作菜单管理
            case "admin/get_menu_info":
            case "admin/menu_submit_action":
            case "admin/menu_delete_action":
                $menuLink = "admin/menu";
                break;
            // 超管：资源类型管理
            case 'admin/get_source_type_list':             // 获取资源类型列表
            case 'admin/save_source_type_action':          // 保存资源类型
            case 'admin/delete_source_type_action':        // 删除资源类型
                $menuLink = 'admin/source_type';
                break;
            // 超管：资源科目管理
            case 'admin/get_source_subject_list':          // 获取资源科目列表
            case 'admin/save_source_subject_action':       // 保存资源科目
            case 'admin/delete_source_subject_action':     // 删除资源科目
                $menuLink = 'admin/source_subject';
                break;
            // 超管：资源出版社管理
            case 'admin/get_source_publisher_list':         // 获取资源出版社列表
            case 'admin/save_source_publisher_action':      // 保存资源出版社
            case 'admin/delete_source_publisher_action':    // 删除资源出版社
                $menuLink = 'admin/source_publisher';
                break;
            // 超管：资源年级管理
            case 'admin/get_source_grade_list':         // 获取资源年级列表
            case 'admin/save_source_grade_action':      // 保存资源年级社
            case 'admin/delete_source_grade_action':    // 删除资源年级社
            case 'admin/get_source_grade_info':         // 获取资源年级详情
                $menuLink = 'admin/source_grade';
                break; 
            // 学校：角色管理
            case "staff/role_submit_action":
            case "staff/get_role_info":
            case "staff/role_delete_action":
            case "staff/get_role_menu":
                $menuLink = "staff/role";
                break;
            // 学校：教师管理
            case "school/get_teacher_list":
            case "school/reset_teacher_password":
            case "school/teacher_edit":
            case "school/save_teacher_action":
            case "school/update_teacher_role":
            case "school/delete_teacher_action":
            case "school/import_realcard":           // 批量导入卡号
            case "import/import_classroom":          // 导入课室
            case "import/import_grade":              // 导入年级
            case "import/import_class":              // 导入班级
            case "import/import_teacher":            // 导入教师
            case "import/import_student":            // 导入学生
            case "import/import_subject":            // 导入科目
            case "import/import_schedule":           // 导入课程
            case "import/import_exam":               // 导入考场安排
            case "import/import_exam_seats":         // 导入考场座位
            case "import/import_grade_result":       // 导入年级成绩     
            case "school/export_teacher":
            case "school/delete_teacher_batch":      // 批量删除教师
            case "import/import_brand_class":        // 导入班牌所属班级
            case "import/import_teacher_coach":      // 导入任课老师数据
            case "import/import_master_coach":       // 导入班主任数据 
                $menuLink = "school/teacher";
                break;
            // 学校：学生管理
            case "school/student_edit":
            case "school/save_student_action":
            case "school/get_student_list":
            case "school/get_date_student_num":          // 获取学校当日人数统计
            case "school/get_work_data_num":             // 获取学校作业量统计
            case "school/reset_student_password":        // 重置学生密码
            case "school/delete_student_action":
            case "school/select_grade_plugin_data_source":    // 选择年级插件数据源
            case "school/batch_update_student_class":         // 批量修改学生班级 
            case "school/select_default_grade_plugin_data_source":    // 选择默认年级插件数据源
            case "school/export_student":               // 导出学生数据
            case "school/unbind_action":                       // 解绑学生卡号
            case "school/export_student_realcard":               // 导出学生数据
            case "school/delete_student_batch":         // 批量删除学生
                $menuLink = "school/student";
                break;
            // 学校：年级管理
            case "classes/save_grade_action":
            case "classes/get_grade_list":
            case "classes/delete_grade":
            case "classes/classes":
            case "classes/classes_edit":
            case "classes/save_class_action":
            case "classes/get_class_list":
            case "classes/delete_class_action":
            case "classes/grade_edit":
            case "classes/export_class_data":     // 导出班级数据
                $menuLink = "classes/grade";
                break;
            // 健康: 健康信息
            case "school/export_health":
            case "school/get_health_list":
                $menuLink = "school/health";
                break;
            // 健康: 健康预警
            case "school/get_health_warn_list":
            case "school/health_warn_edit":
            case "school/save_health_warn_action":
            case "school/delete_health_warn_action":
                $menuLink = "school/health_warn";
                break;
            // 健康: 健康统计
            // case "school/export_health":
                $menuLink = "school/health_statistics";
                break;
            // 学校：班级作业
            case "contents/get_homework_class_list":
            case "contents/homework_list":
            case "contents/get_homework_list":
            case "contents/homework_edit":
            case "contents/save_homework_action":
            case "contents/delete_homework_action":
            case "contents/delete_homework_batch":       // 批量删除作业
                $menuLink = "contents/homework";
                break;
            // 学校：班级动态
            case "contents/get_news_class_list":
            case "contents/news_list":
            case "contents/get_news_list":
            case "contents/news_edit":
            case "contents/save_news_action":
            case "contents/delete_news_action":
            case "contents/delete_news_batch":       // 批量删除动态
                $menuLink = "contents/news";
                break;
            // 学校：班级通知
            case "contents/get_notify_class_list":
            case "contents/notify_list":
            case "contents/get_notify_list":
            case "contents/notify_edit":
            case "contents/save_notify_action":
            case "contents/delete_notify_action":
            case "contents/delete_notify_batch":       // 批量删除通知
                $menuLink = "contents/notify";
                break;
            // 学校：班级视频
            case "contents/get_video_class_list":
            case "contents/video_list":
            case "contents/get_video_list":
            case "contents/video_edit":
            case "contents/save_video_action":
            case "contents/delete_video_action": 
                $menuLink = "contents/video";
                break;
            // 学校：校园公告
            case "contents/get_announce_list":
            case "contents/announce_edit":
            case "contents/save_announce_action":
            case "contents/delete_announce_action": 
                $menuLink = "contents/announce";
                break;
            // 学校：班级主题
            case "contents/subject_content_list":
            case "contents/get_subject_content_list":
            case "contents/subject_content_edit":
            case "contents/save_subject_content_action":
            case "contents/delete_subject_content_action":
                $menuLink = "contents/subject_content";
                break;
            // 学校：课程管理
            case "school/get_lesson_list":
            case "school/save_lesson_action":
            case "school/delete_lesson_action":
            case "school/delete_subject_batch":       // 批量删除科目
            case "school/export_subject_data":     // 导出科目数据
                $menuLink = "school/lesson";
                break;
            // 学校：课室管理
            case "classes/get_classroom_list":
            case "classes/save_classroom_action":
            case "classes/delete_classroom_action":
            case "school/delete_classroom_batch":      // 批量删除课室
            case "classes/export_classroom_data":      // 导出课室数据                
                $menuLink = "classes/classroom";
                break;
            // 学校： 课程表管理
            case "contents/get_schedule_class_list":        // 获取班级课程列表
            case "contents/schedule_table":                 // 课程列表页面
            case "schedule/save_schedule_lesson":           // 编辑课程页面
            case "schedule/save_schedule_lesson_action":    // 保存课程
            case "schedule/delete_schedule_lesson_action":  // 删除课程
            case "schedule/delete_class_lessons_action":    // 删除班级课程
            case 'schedule/save_schedule':                  // 编辑课程模板页面
            case 'schedule/save_schedule2':                  // 编辑课程模板页面
            case 'schedule/save_schedule_action':           // 保存课程模板

            case 'schedule/import':
            case 'schedule/export':
            case 'schedule/import_teaching':                // 导入走班课表
            case 'schedule/export_teaching':                // 导出走班课表模板

            case "contents/grade_schedule":                 // 年级课表模板列表页面
            case "contents/grade_schedule_detail":          // 年级课表模板详情页面
            case "contents/toggle_grade_schedule_action":   // 开启不同年级作息
            case "contents/auto_complete_schedule_teacher": // 自动填充任课教师
                $menuLink = "contents/schedule";
                break;
            // 学校： 考试安排
            case "contents/exam_room":                                  // 查看考场座位
            case "contents/edit_exam_entry_time":                       // 修改考试进场时间
            // 学校： 考试数据管理
            case "contents/exam_data":                                  // 考试批次页面
            case "contents/get_exam_list":                              // 获取考试批次列表
            case "contents/exam_room_data":                             // 考试列表页面
            case "contents/get_exam_room_list":                         // 获取考试列表
            case "contents/exam_room_detail_data":                      // 考场列表页面
            case "contents/save_exam_action":                           // 保存批次
            case "contents/delete_exam_action":                         // 删除批次
            case "contents/save_exam_room_page":                        // 编辑考试表单页面
            case "contents/save_exam_room_action":                      // 保存考试
            case "contents/delete_exam_room_action":                    // 删除考试
            case "contents/save_exam_room_detail_page":                 // 编辑考场表单页面
            case "contents/save_exam_room_detail_action":               // 保存考场
            case "contents/delete_exam_room_detail_action":             // 删除考场
            case "contents/get_exam_room_detail_by_roomid":             // 获取某考试的考场
            case "contents/exam_room_detail_student_data":              // 考场座位页面
            case "contents/get_exam_room_detail_student_list":          // 获取考场座位
            case "contents/select_student_plugin_data_source":          // 获取学生选择控件
            case "contents/save_exam_student_action":                   // 保存考试学生座位
            case "contents/edit_exam_student_action":                   // 修改考试学生座位
            case "contents/delete_exam_student_action":                 // 删除考试学生座位
                $menuLink = "contents/exam";
                break;
            // 学校：学生成绩 
            case "contents/get_result_major_list":          // 获取成绩大项列表
            case "contents/save_result_major_action": //保存成绩大项
            case "contents/delete_result_major_action": //删除成绩大项
            case "contents/result_grade_data":      // 成绩年级项页面
            case "contents/get_result_grade_list": // 获取年级项列表
            case "contents/edit_result_grade_page": // 编辑年级项页面
            case "contents/save_result_grade_action": //保存年级项
            case "contents/delete_result_grade_action": // 删除年级项
            case "contents/result_data":      // 成绩列表页面
            case "contents/get_result_list": // 获取成绩列表
            case "contents/edit_result_page": // 编辑成绩页面
            case "contents/save_result_action": //保存成绩
            case "contents/delete_result_action": // 删除成绩
            case "contents/export_grade_result":  // 导出年级成绩模板
            case "contents/notify_grade_result":  // 发送成绩通知
                $menuLink = "contents/result_major_data";
                break;
            // 学校：班牌管理
            case "brand/get_brand_list":
            case "brand/save_brand_action":
            case "brand/screen_shot":       // 远程截屏
            case "brand/quit":              // 远程退出
            case "brand/power_off":         // 远程关机
            case "brand/power_restart":     // 远程重启
            case "brand/get_power_time":    // 获取开关机时间
            case "brand/save_power_time":   // 设置开关机时间
            case "brand/get_version":       // 获取设备版本
            case "brand/update_version":    // 更新设备版本
            case "brand/get_sign_data":     // 获取本地缓存数据
            case "brand/save_brand_zoom_action":        // 保存设备缩放倍数
            case "brand/save_brand_sign_interval_action":     // 保存考勤进入时间
            case "brand/save_default_brand_paw":        // 保存班牌默认登录密码
            case "brand/save_batch_allow_send":         // 批量设置对话留言内容发送
            case "brand/save_brand_class_action":         // 保存班牌对应班级
            case "brand/export_brand_class": 
                $menuLink = "brand/index";
                break;
            // 学校：班牌定时开关机
            case "brand/get_power_holiday":           // 获取学校放假定时失效时间
            case "brand/save_power_holiday":          // 保存学校放假定时失效时间
            case "brand/get_power_week":              // 获取学校每周定时失效时间
            case "brand/save_power_week":             // 保存学校每周定时生效时间
            case "brand/notify_brand_update":         // 推送班牌更新通知
            case "brand/notify_brand_restart":         // 推送班牌更新通知
            case "brand/grade_power_time":             // 设置年级开关机时间
            case "brand/get_grade_power_time_list":    // 获取年级开关机时间列表
            case "brand/get_grade_power_time":         // 获取年级开关机时间
            case "brand/get_grade_power_time":         // 保存年级开关机时间
            case "brand/save_grade_power_time":        // 保存年级开关机时间
            case "brand/get_power_time_v2_for_day":    // 获取周几的定时开关机时间v2
            case "brand/save_power_time_v2":           // 设置开关机时间v2
            case "brand/brand_power_time":             // 班牌修改开关机时间页面
            case "brand/grade_power_time_detail":      // 年级开关机时间页面
            case "brand/get_grade_power_time_for_day": // 获取周几的年级定时开关机时间v2
            case "brand/reset_power_time_v2":          // 重置默认时间
            case "brand/power_time_batch_v2":          // 批量设置开关机时间页面    
            case "brand/save_power_time_batch_v2":     // 批量设置开关机时间v2
                $menuLink = "brand/power_time";
                break;
            // 学校：外部链接
            case "brand/get_custom_menu_list":         // 获取学校外部链接
            case "brand/edit_custom_menu":             // 编辑学校外部链接页面
            case "brand/save_custom_menu_action":      // 保存学校外部链接
            case "brand/delete_custom_menu_action":    // 删除学校外部链接
                $menuLink = "brand/custom_menu";
                    break;
            // 学校：相册管理
            case "contents/get_album_class_list":
            case "contents/album_list":
            case "contents/save_category_action":
            case "contents/save_image_action":
            case "contents/delete_album_image":
            case "contents/delete_album_category":
            case "contents/album_list_by_admin":
            case "contents/album_by_admin_edit":
            case "contents/save_album_by_admin_action":
            case "contents/delete_album_by_admin_action":
            case "contents/get_category_by_admin_list":
                $menuLink = "contents/album";
                break;
            // 学校：班级荣誉
            case "contents/honor_list":
            case "contents/get_honor_class_list":
            case "contents/save_honor_action":
            case "contents/delete_honor_image":
                $menuLink = "contents/honor";
                break;
            // 集约化：信息发布管理
            case "cms/article_edit":
            case "cms/get_article_list":
            case "cms/save_article_action":
            case "cms/delete_article_action":
                $menuLink = "cms/index";
                break;
            // 集约化：网址栏目管理
            case "cms/save_category_action":
            case "cms/delete_category_action":
            case "cms/category_edit":
                $menuLink = "cms/category";
                break;
            // 集约化：幻灯片管理
            case "cms/get_slider_list":
            case "cms/save_slider_action":
            case "cms/delete_slider_action":
                $menuLink = "cms/slider";
                break;
            // 集约化：友情链接管理
            case "cms/get_link_list":
            case "cms/save_link_action":
            case "cms/delete_link_action":
                $menuLink = "cms/link";
                break;
            // 集约化：官网设置
            case "cms/save_cms_setting":
                $menuLink = "cms/setting";
                break;
            // 数据管理：学生考勤数据管理
            case "data/get_sign_class_list":
            case "data/sign_data":
            case "data/student_sign_today":
            case "data/get_student_sign_list":
            case "data/export_student_sign":
            case "data/export_student_sign_img":    
                $menuLink = "data/student_sign";
                break;
            // 数据管理：教师考勤数据管理
            case "data/get_teacher_sign_list":    
                $menuLink = "data/teacher_sign";
                break;
            // 学校管理：基础设置
            case "setting/save_setting":
                $menuLink = "setting/index";
                break;
            // 内部邮件：写信
            case "mail/save_mail_action":
                $menuLink = "mail/mail_edit";
                break;
            // 内部邮件：已发送
            case "mail/get_send_mail":
            case "mail/delete_mail_action":
                $menuLink = "mail/send";
                break;
            // 内部邮件：收件箱
            case "mail/get_mail_list":
                $menuLink = "mail/index";
                break;
            // 内部邮件：通用
            case "mail/mail_info":
            case "mail/get_mail_user":
                $menuLink = "mail";
                break;
            // 工作流： 流程设计和发起申请  
            case "workflow/get_process_list":
                $menuLink = array(
                    'workflow/process',
                    "workflow/create"
                );
                break;
            // 工作流：流程设计
            case "workflow/save_process_action":
            case "workflow/edit_process_form":
            case "workflow/save_workflow_form":
            case "workflow/edit_process":
            case "workflow/save_workflow_process":
            case "workflow/delete_workflow":
                $menuLink = "workflow/process";
                break;
            // 工作流：发起申请
            case "workflow/check_process_form":
            case "workflow/check_process":
            case "workflow/create_application":  // 发起申请页面
            case "workflow/save_application":    // 提交申请
                $menuLink = "workflow/create";
                break;
            // 工作流：我发起的申请
            case "workflow/get_user_application_list": // 我发起的申请页面
            case "workflow/check_application_by_user": // 查看申请内容
            case "workflow/edit_application":          // 修改申请
            case "workflow/save_edit_application":     // 保存修改申请
            case "workflow/delete_application":        // 删除申请成功
                $menuLink = "workflow/my_create";
                break;
            // 工作流：我处理的申请
            case "workflow/get_handling_application_list":        // 待处理的申请页面
            case "workflow/check_application_by_handling_user":   // 查看申请内容
            case "workflow/accept_application":                   // 通过申请
            case "workflow/refuse_application":                   // 拒绝申请
                $menuLink = "workflow/my_handling";
                break;
            // 工作流：已处理的申请
            case "workflow/get_handled_application_list":        // 已处理的申请页面
            case "workflow/check_application_by_handled_user":   // 查看申请内容
                $menuLink = "workflow/my_handled";
                break;
            // 教育资源：资源检索
            case 'source/get_source_list_for_check':             // 获取资源列表
            case 'source/detail':                         // 资源详情页面
                $menuLink = 'source/check';
                break;
            // 教育资源：资源管理
            case 'source/get_source_list':                       // 获取资源列表
            case 'source/get_source_info':                       // 获取资源详情
            case 'source/upload_source':                         // 上传资源
            case 'source/select_source_grade_plugin_data_source':// 选择资源年级插件数据源
            // case 'source/delete_upyun_file':                  // 删除又拍云文件
            case 'source/save_source_action':                    // 保存资源
            case 'source/source_preview':                        // 资源预览
            case 'source/source_delete_action':                  // 删除资源
            case 'source/verify_source':                         // 审核资源  
                $menuLink = "source/manage";
                break;
            // 移动端管理：轮播图管理
            case "wx/get_banner_list":
            case "wx/save_banner_action":
            case "wx/delete_banner_action":
                $menuLink = "wx/banner";
                break;
            // 德育管理：德育动态栏目管理
            case "moral/get_subject_list":
            case "moral/save_subject_action":
            case "moral/delete_subject_action":
                $menuLink = "moral/timeline_subject";
                break;
            // 德育管理：德育动态管理
            case "moral/get_timeline_list":
            case "moral/save_timeline_action":
            case "moral/delete_timeline_action":
            case "moral/timeline_edit":    
                $menuLink = "moral/timeline";
                break;
            // 德育管理：德育活动管理
            case "moral/get_activity_list":
            case "moral/save_activity_action":
            case "moral/delete_activity_action":
            case "moral/activity_edit":
            case "moral/activity_detail":
            case "moral/reject_activity_action":
            case "moral/accept_activity_action":
                $menuLink = "moral/activity";
                break;
            // 德育管理：评价结果管理
            case "moral/get_result_list":
            case "moral/save_result_action":
            case "moral/delete_result_action":
                $menuLink = "moral/remark_result";
            break;
            // 德育管理：评价管理
            case "moral/get_remark_list":
            case "moral/save_remark_action":
            case "moral/delete_remark_action":
            case "moral/remark_edit":    
                $menuLink = "moral/remark";
            break;
            // 执教关系
            case "staff/get_coach_list":
            case "staff/save_coach_action":
            case "staff/delete_coach_action":
            case "staff/coach_edit":
            case "staff/export_teacher_coach":    // 导出执教老师模板
            case "staff/export_master_coach":    // 导出班主任模板
                $menuLink = "staff/coach";
            break;
            // 学校：卡号激活记录
            case "school/get_charge_pay_list":
            case "school/export_charge_pay":        // 导出激活记录数据
            case "school/get_charge_pay_total":     // 合计缴费
                $menuLink = "school/charge_pay";
                break;
            // 学校：卡号人工激活
            case "school/artificial_activate":      // 人工激活操作
                $menuLink = "school/charge_artificial";
                break;
            // 学校：闸机管理
            case "school/get_gate_list":
            case "school/save_gate_action":
            case "school/delete_gate_action":
                $menuLink = "school/gate";
                break;
            // 学校：闸机任务管理
            case "school/get_gate_task_list":
                $menuLink = "school/gate_task";
                break;
            // 学校：学生账号管理
            case "school/get_student_list_for_account":
            case "school/update_student_limit_action":
            case "school/update_student_limit_batch_action":    
                $menuLink = "school/student_account";
                break;
            // 学校：日志管理
            case "setting/get_log_list":
                $menuLink = "setting/log";
                break;
            // 学校：一体机管理
            case "school/get_aio_list":
            case "school/save_aio_action":
            case "school/delete_aio_action":
                $menuLink = "school/aio";
                break;
            // 学校：一体机任务管理
            case "school/get_aio_task_list":
                $menuLink = "school/aio_task";
                break;
            // 学校：智能门锁管理
            case "school/get_smart_lock_list":
            case "school/save_smart_lock_action":
            case "school/delete_smart_lock_action":
            case "school/get_student_list_for_smart_lock":
            case "school/add_smart_lock_student_white_list_action":
            case "school/delete_smart_lock_student_white_list_action":
            case "school/add_smart_lock_student_white_list_batch_action":
            case "school/delete_smart_lock_student_white_list_batch_action":
            case "school/get_smart_lock_unlock_record_list":    
                $menuLink = "school/smart_lock";
                break;
            // 学校：食谱管理
            case "data/get_recipe_list":
            case "data/save_recipe":
            case "data/save_recipe_action":
            case "data/delete_recipe_action":
            case "data/recipe_detail":
            case "data/save_recipe_detail_action":
            case "data/delete_recipe_detail_action":
                $menuLink = "data/recipe";
                break;
            // 学校：菜品分类管理
            case "data/get_recipe_cate_list":
            case "data/save_recipe_cate_action":
            case "data/delete_recipe_cate_action":
                $menuLink = "data/recipe_cate";
                break;
        }

        $userInfo = $this->session->rmxUser;
        // 判断权限是否是数组
        if(is_array($menuLink)){
            $hasRole = false;
            foreach($menuLink as $value){
                if(in_array($value, $userInfo['roleArray'])){
                    $hasRole = true;
                }
            }
            if(false === $hasRole){
                show_error("抱歉，您没有权限访问");
            }
        } else{
            if(!in_array($menuLink, $userInfo['roleArray'])) show_error("抱歉，您没有权限访问");
        }
    }

    // 获取通知班级名串私有方法，可给子类使用
    protected function _get_class_name_str($classIds) {
        $classIdArr = explode(',', $classIds);
        $classIdArr = array_unique($classIdArr);
        $classNameArr = array();
        foreach($classIdArr as $id) {
            $class = $this->classesModel->get_class_info($id);
            if($class) {
                array_push($classNameArr, $class['class_name']);
            }
        }
        return implode('、', $classNameArr);
    }

     // 获取学生姓名串私有方法，可给子类使用
     protected function _get_student_name_str($studentIds) {
        $studentIdArr = explode(',', $studentIds);
        $studentIdArr = array_unique($studentIdArr);
        $studentArr = array();
        $studentNameArr = array();
        foreach($studentIdArr as $id) {
            $student = $this->schoolModel->get_student_info($id);
            // 获取首字母
            $student['realnameFirstChar'] = getFirstChar($student['realname']);
            array_push($studentArr, $student);
        }
        // 按姓名首字母排序
        $timeKey =  array_column($studentArr, 'realnameFirstChar');
        array_multisort($timeKey, SORT_ASC, $studentArr);
        foreach($studentArr as $student) {
            array_push($studentNameArr, $student['realname']);
        }

        return implode('、', $studentNameArr);
    }

    // 通过班级id集合获取班级信息集合（改版执教关系）
    // 年级管理员，任课班级是年级所有班级
    protected function get_classes_by_teacher_id($excludeMaster=false, $onlyNormalType = true) {
        // if(empty($this->user['class_ids'])) {
        //     return array();
        // }
        // $classIdArr = explode(',', $classIds);
        // $teacherClassArr = array();
        // foreach($classIdArr as $classId) {
        //     // 获取班级信息
        //     $class = $this->classesModel->get_class_info($classId);
        //     if($class) {
        //         array_push($teacherClassArr, $class);
        //     }
        // }
        // return $teacherClassArr;

        $this->load->model('staffModel');
        // 获取班级列表
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $this->user['school_id'];
        $classList = $this->classesModel->get_class_list($classParams);
        // 使用id作为键
        $classList = array_value_to_key($classList, 'id');

        // 管理员可管理所有班级，只获取行政班
        if($this->user['user_type'] == USER_TYPE_SCHOOL) {
            $normalClassParams = $classParams;
            $normalClassParams['classType'] = CLASSES_TYPE_NORMAL;
            $classList = $this->classesModel->get_class_list($normalClassParams);

            // 按班级名排序
            $timeKey =  array_column($classList, 'class_name');
            array_multisort($timeKey, SORT_ASC, $classList);

            // 按sort值排序
            $timeKey =  array_column($classList, 'sort_level');
            array_multisort($timeKey, SORT_DESC, $classList);
            return $classList;
        }

        // 获取执教关系列表
        $coachParams['teacherId'] = $this->user['id'];
        if($excludeMaster) {
            // 是否排除班主任关系
            $coachParams['notCoachType'] = COACH_TYPE_MASTER;
        }
        $coachList = $this->staffModel->get_coach_list($coachParams);
        // echo '<pre>';var_export($coachList);exit;
        return $this->getTeacherClassByCoachList($coachList, $this->user['school_id'], $onlyNormalType)['teacherClassArr'];
    }

    // 通过coachList获取任课班级
    protected function getTeacherClassByCoachList($coachList, $schoolId, $onlyNormalType = false) {
        $teacherClassIdArr = array();
        $teacherClassArr = array();
        if($coachList) {
            // 获取行政班级列表
            $classParams['isDelete'] = 0;
            $classParams['schoolId'] = $schoolId;
            // 默认只获取行政班
            if($onlyNormalType) {
                $classParams['classType'] = CLASSES_TYPE_NORMAL;
            }

            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键
            $classList = array_value_to_key($classList, 'id');
            foreach($coachList as $coach) {
                if($coach['coach_type'] == COACH_TYPE_GRADE_ADMIN) {
                    // 年级管理员，任课班级为整个年级班级
                    $gradeId = $coach['grade_id'];
                    if($gradeId) {
                        // 只获取行政班
                        $gradeClassList = $this->classesModel->get_class_list_by_grade($gradeId, CLASSES_TYPE_NORMAL);
                        foreach($gradeClassList as $v) {
                            if(isset($classList[$v['id']]) && !in_array($v['id'], $teacherClassIdArr))
                            array_push($teacherClassIdArr, $v['id']);
                        }
                    }
                } elseif($coach['coach_type'] == COACH_TYPE_SCHOOL_ADMIN) {
                   // 学校管理员，任课班级为整个学校班级，只获取行政班
                   $normalClassParams['isDelete'] = 0;
                   $normalClassParams['schoolId'] = $schoolId;
                   $normalClassParams['classType'] = CLASSES_TYPE_NORMAL;
                   $normalClassList = $this->classesModel->get_class_list($normalClassParams);
             
                   foreach($normalClassList as $class) {
                       array_push($teacherClassIdArr, $class['id']);
                   }
                    break;
                } else {
                    $idArr = explode(',', $coach['class_ids']);
                    foreach($idArr as $id) {
                        if(isset($classList[$id]) && !in_array($id, $teacherClassIdArr)) {
                            array_push($teacherClassIdArr, $id);
                        }
                    }
                }
            }
        }
        if($teacherClassIdArr) {
            foreach($teacherClassIdArr as $teacherClassId) {
                if(isset($classList[$teacherClassId])) {
                    $classList[$teacherClassId]['name'] = $classList[$teacherClassId]['class_name'];
                    array_push($teacherClassArr, $classList[$teacherClassId]);
                }
            }
            if($teacherClassArr) {
                // 按班级名排序
                $timeKey =  array_column($teacherClassArr, 'class_name');
                array_multisort($timeKey, SORT_ASC, $teacherClassArr);
                // 按sort值排序
                $timeKey =  array_column($teacherClassArr, 'sort_level');
                array_multisort($timeKey, SORT_DESC, $teacherClassArr);
            }
        }
        
        // echo'<pre>';var_export($teacherClassIdArr);var_export($teacherClassArr);exit;
        return array(
            'teacherClassIdArr' => $teacherClassIdArr,
            'teacherClassArr' => $teacherClassArr
        );
    }

    // 判断是否学校管理员
    protected function checkIsSchoolAdminByCoachList($coachList) {
        $isSchoolAdmin = false;
        foreach($coachList as $coach) {
            if($coach['coach_type'] == COACH_TYPE_SCHOOL_ADMIN) {
                $isSchoolAdmin = true;
                break;
            }
        }
        return $isSchoolAdmin;
    }

    // 判断教师对某个班级是否有权限
    protected function checkTeacherRoleByClass($classId) {
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            if(!in_array($classId, $this->rmxUser['classIdArr'])) {
                throw new Exception('权限不足');
             }
        }
    }

    // 判断教师对某个班牌是否有权限
    protected function checkTeacherRoleByBrand($brandId) {
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $brand = $this->classesModel->get_brand_info($brandId);
            if(empty($brand) || !in_array($brand['class_id'], $this->rmxUser['classIdArr'])) {
                throw new Exception('权限不足');
             }
        }
    }

    // 获取作业未读数
    protected function _get_homework_unread() {
        if($this->bindUserType != BIND_TYPE_STUDENT) {
            return array(
                'items' => array(),
                'count' => 0
            );
        }
        $classId = isset($this->user['class']['id']) ? $this->user['class']['id'] : 0;
        $params['classId'] = $classId;
        $params['isDelete'] = 0;
        $params['field'] = 'id, homework_title, homework_content, updatetime';
        $homeworkList = $this->contentModel->get_homework_list($params);
        if(empty($homeworkList)) {
            return array(
                'items' => array(),
                'count' => 0
            );
        }
        // 以id为下标
        $homeworkList = array_value_to_key($homeworkList, 'id');
        // 过滤已读项
        $homeworkList = $this->_filter_read($homeworkList, BIND_TYPE_STUDENT, READ_TYPE_HOMEWORK);
        return array(
            'items' => $homeworkList,
            'count' => count($homeworkList)
        );
    }

    // 获取邮件未读数
    protected function _get_mail_unread() {
        if($this->bindUserType != BIND_TYPE_TEACHER) {
            return array(
                'items' => array(),
                'count' => 0
            );
        }
        // 获取邮件列表
        $params['schoolId'] = $this->user['school_id'];
        $params['isDelete'] = 0;
        $params['toUser'] = $this->user['id'];
        $mailList = $this->contentModel->get_mail_list($params);
        if(empty($mailList)) {
            return array(
                'items' => array(),
                'count' => 0
            );
        }
        // 以id为下标
        $mailList = array_value_to_key($mailList, 'id');
        // 过滤已读项
        $mailList = $this->_filter_read($mailList, BIND_TYPE_TEACHER, READ_TYPE_MAIL);
        return array(
            'items' => $mailList,
            'count' => count($mailList)
        );
    }

    // 获取审批未读数
    protected function _get_application_unread() {
        if($this->bindUserType != BIND_TYPE_TEACHER) {
            return array(
                'items' => array(),
                'count' => 0
            );
        }
        // 获取邮件列表
        $params['schoolId'] = $this->user['school_id'];
        $params['isDelete'] = 0;
        $params['handleUserId'] = $this->user['id'];
        $params['state'] = APPLICATION_PENDING;
        $appliList = $this->workflowModel->get_workflow_application_list($params);
        if(empty($appliList)) {
            return array(
                'items' => array(),
                'count' => 0
            );
        }
        // 以id为下标
        $appliList = array_value_to_key($appliList, 'id');
        // 过滤已读项
        $appliList = $this->_filter_read($appliList, BIND_TYPE_TEACHER, READ_TYPE_APPLICATION);
        return array(
            'items' => $appliList,
            'count' => count($appliList)
        );
    }

    // 获取班牌留言未读数
    protected function _get_note_unread($isBrand) {
        $noteList = $this->wxUserModel->get_user_wx_note_list($this->user['id'], $this->bindUserType, $isBrand);
        $unreadCount = 0;
        foreach($noteList as $note) {
            if($isBrand == 1 && $this->bindUserType == BIND_TYPE_STUDENT) {
                // 家长班牌留言
                // 计算未读数
                if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['receive_user_id'] == $this->user['id'] && $note['send_user_id'] == $this->user['id'] && $note['is_parent'] == 0) {
                    $unreadCount ++;
                }
            } else {
                // 计算未读数
                if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['receive_user_id'] == $this->user['id']) {
                    $unreadCount ++;
                }
            }
        }
        return $unreadCount;
    }

    // 标记已读
    protected function _mark_read($type, $id, $user, $bindUserType) {
        $params['userId'] = $user['id'];
        $params['bindUserType'] = $bindUserType;
        $params['itemId'] = $id;
        $params['itemType'] =$type;
        $read = $this->wxUserModel->get_wx_user_read_list($params);
        if(empty($read)) {
            // 插入已读
            $this->db->insert(WxUserModel::$wxUserReadTable, array(
                'school_id' => $user['school_id'],
                'user_id' => $user['id'],
                'bind_user_type' => $bindUserType,
                'item_id' => $id,
                'item_type' => $type,
                'createtime' => date('Y-m-d H:i:s')
            ));
        }
        return;
    }

    // 过滤已读项
    private function _filter_read($list, $bindType, $readType) {
        // 获取已读作业列表
        $readParams['userId'] = $this->user['id'];
        $readParams['bindUserType'] = $bindType;
        $readParams['itemType'] = $readType;
        $readList = $this->wxUserModel->get_wx_user_read_list($readParams);
        // 判断是否已读
        foreach($readList as $read) {
            if(isset($list[$read['item_id']])) {
                // 过滤已读
                unset($list[$read['item_id']]);
            }
        }
        return $list;
    }

    // 计算下次关机和开机时间v2
    protected function _get_power_time_v2($powerTimeV2Json, $holidayJson) {
        $shutdownTime = '';
        $startupTime = '';
        $holidayArr = json_decode($holidayJson, true);
        $powerTimeV2Arr = json_decode($powerTimeV2Json, true);
        // 如果全周未设置，返回空
        if(empty($powerTimeV2Arr) || (empty($powerTimeV2Arr[1]) && empty($powerTimeV2Arr[2]) && empty($powerTimeV2Arr[3]) && empty($powerTimeV2Arr[4]) 
        && empty($powerTimeV2Arr[5]) && empty($powerTimeV2Arr[6]) && empty($powerTimeV2Arr[7]))) {
            return array(
                'shutdownTime' => $shutdownTime,
                'startupTime' => $startupTime
            );
        }

        $timestamp = time();
        // $timestamp = strtotime('2020-10-27 4:00:00');
        $date = date('Y-m-d', $timestamp);
        // 两分钟后关机
        // $offsetSec = 120;
        // 暂时不设置两分钟后
        $offsetSec = 0;
        // 判断是否放假期间
        if($this->_get_after_holiday_date($timestamp, $holidayArr)) {
            // 放假期间
            $shutdownTime = date('Y-m-d H:i:s', $timestamp + $offsetSec);
        } else {
            // 是否关机日期
            if($powerTimeV2Arr) {
                $i = 1; // 最多循环30次
                $loop = true;
                // 获取关机时间
                while($loop && $i <= 30) {
                    // 存入数据库数值加一
                    $weekInc = date('w', strtotime($date)) + 1;
                    if(isset($powerTimeV2Arr[$weekInc]) && $powerTimeV2Arr[$weekInc]) {
                        foreach($powerTimeV2Arr[$weekInc] as $v) {
                            $startTime = handle_time_length($v['starttime']);
                            $endTime = handle_time_length($v['endtime']);
                            $startDatetime = $date . ' ' . $startTime . ':00';
                            $endDatetime = $date . ' ' . $endTime . ':00';
    
                            if($timestamp >= strtotime($startDatetime)) {
                                if($timestamp <= strtotime($endDatetime)) {
                                    // 当前是开机时间
                                    $shutdownTime = $endDatetime;
                                    $loop = false;
                                    break;
                                } else {
                                    // 循环下次时间段
                                }
                            } else {
                              // 当前是关机时间，2分钟后关机
                              $shutdownTime = date('Y-m-d H:i:s', $timestamp + $offsetSec);
                              $loop = false;
                              break;
                            }
                            // var_export($endDatetime);exit;
                        }
                    } else {
                        // 全天关机，2分钟后关机
                        $shutdownTime = date('Y-m-d H:i:s', $timestamp + $offsetSec);
                        $loop = false;
                    }
                    // 循环下个日期
                    // 日期+1
                    $date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
                    $i++;
                }
            }
        }              

        // 如果关机时间为空，开机时间也为空
        if($shutdownTime) {
            $i2 = 1; // 最多循环400次，满足1年的假期
            $loop2 = true;
            $shutdownTimestamp = strtotime($shutdownTime);
            $shutdownDate = date('Y-m-d', $shutdownTimestamp);

            // 计算开机时间
            while($loop2 && $i2 <= 400) {
                // 存入数据库数值加一
                $weekInc = date('w', strtotime($shutdownDate)) + 1;

                if(isset($powerTimeV2Arr[$weekInc]) && $powerTimeV2Arr[$weekInc] && is_array($powerTimeV2Arr[$weekInc])) {
                    foreach($powerTimeV2Arr[$weekInc] as $v) {
                        $startTime = handle_time_length($v['starttime']);
                        $endTime = handle_time_length($v['endtime']);
                        $startDatetime = $shutdownDate . ' ' . $startTime . ':00';
                        $endDatetime = $shutdownDate . ' ' . $endTime . ':00';

                        if($shutdownTimestamp <= strtotime($startDatetime)) {
                            // 判断是否放假期间
                            if(empty($this->_get_after_holiday_date(strtotime($startDatetime), $holidayArr))) {
                                $startupTime = $startDatetime;
                                $loop2 = false;
                                break;
                            }
                        }
                    }
                }
                // 循环下个日期
                // 日期+1
                $shutdownDate = date('Y-m-d', strtotime('+1 day', strtotime($shutdownDate)));
                $i2++;
            }
        }
        return array(
            'shutdownTime' => $shutdownTime,
            'startupTime' => $startupTime
        );
    }

    // 判断某天是否在放假期间，不是：返回空字符串；是：返回放假后日期
    private function _get_after_holiday_date($timestamp, $holidayArr) {
        $res = '';
        if($holidayArr) {
            foreach($holidayArr as $holiday) {
                $startDate = $holiday['startdate'] . ' 00:00:00';
                $endDate = $holiday['enddate'] . ' 23:59:59';
                if($timestamp >= strtotime($startDate) && $timestamp <= strtotime($endDate)) {
                    // 放假期间，返回放假后的日期
                    $res = date('Y-m-d', strtotime('+1 day', strtotime($holiday['enddate'])));
                }
            }
        }
        return $res;
    }

    // 默认开关机时间v2
    protected function _get_default_power_time_v2_json() {
        $arr = array(
            '1' => array(),
            '2' => array(
                array(
                    'starttime' => '5:00',
                    'endtime' => '19:00'
                )
            ),
            '3' => array(
                array(
                    'starttime' => '5:00',
                    'endtime' => '19:00'
                )
            ),
            '4' => array(
                array(
                    'starttime' => '5:00',
                    'endtime' => '19:00'
                )
            ),
            '5' => array(
                array(
                    'starttime' => '5:00',
                    'endtime' => '19:00'
                )
            ),
            '6' => array(
                array(
                    'starttime' => '5:00',
                    'endtime' => '19:00'
                )
            ),
            '7' => array()
        );
        return json_encode($arr, JSON_UNESCAPED_UNICODE);
    }
}
